package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 聊天室客户端：将客户端说的过程定义在了线程里，并在start方法里启用线程
 *
 * @author XingHaiYang
 * @date 2022/9/15 17:06
 */
public class Client2 {
    private Socket s;

    public Client2() {
        try {
            System.out.println("客户端正在连接服务器...");
            s = new Socket("localhost", 8088);
            System.out.println("客户端连接服务器成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        Runnable r = new ServerHandler();
        Thread t = new Thread(r);
        t.start();
    }

    public static void main(String[] args) {
        Client2 c2 = new Client2();
        c2.start();
    }

    private class ServerHandler implements Runnable{
        @Override
        public void run() {
            try {
                OutputStream out = s.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                PrintWriter pw = new PrintWriter(bw);
                Scanner scan = new Scanner(System.in);
                while(true){
                    String say = scan.nextLine();
                    if("exit".equals(say)){
                        break;
                    }
                    System.out.println("客户端说："+say);
                    pw.println(say);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
